#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO_NAME "/tmp/my_fifo"
char * ReadSpeacialLine(int i,int pipe_fd)
{
        int WhichLine=i;             //指定要读取哪一行
        int CurrentIndex=0;             //当前读取的行
        char str[1024];             //每行最大读取的字符数,可根据实际情况扩大
        FILE *fpp = fopen("/var/log/usermonitor/usermonitor.log","r"); //判断文件是否存在及可读
        while (!feof(fpp))
        {
                if (CurrentIndex==WhichLine)
                {
                        fgets(str,1024,fpp);  //读取一行
                        write(pipe_fd,str,sizeof(str));
                        return str;
                }
                fgets(str,1024,fpp);
                CurrentIndex++;
        }
        fclose(fpp);                     //关闭文件
        return NULL;
}
int get_line()
{
        int c;
        FILE *fp;
        int lines=0;
        fp=fopen("/var/log/usermonitor/usermonitor.log", "r");
        if(fp)
        {
                while((c=fgetc(fp)) != EOF)
                        if(c=='\n') lines++;
                fclose(fp);
        }
        return lines;
}
void main(){
        int pipe_fd;
        int res;
        if (access(FIFO_NAME, F_OK) == -1)
        {
                res = mkfifo(FIFO_NAME, 0766);
                if (res != 0)
                {
                        fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);
                        exit(EXIT_FAILURE);
                }
        }
        printf("Process %d opening FIFO O_WRONLY\n", getpid());
        pipe_fd = open(FIFO_NAME, O_WRONLY);
        printf("the file's descriptor is %d\n", pipe_fd);
        int i = 0;
        int lines = 0;
        int old_lines = 0;
        char strline[1024];
        FILE *ff;
        while(i<2000){
                i++;
                old_lines = lines;
                lines = get_line();
                if(lines == old_lines||old_lines == 0){
                        if(lines >10){
                                ff = fopen("/var/log/usermonitor/usermonitor.log","w+");
                                if(!feof(ff)){
                                        lines = 0;
                                        printf("%s\n","update history!");
                                }else{
                                }
                                fclose(ff);
                        }
                }else{
                        old_lines++;
                        lines = old_lines;
                        ReadSpeacialLine(old_lines,pipe_fd);
                }
                sleep(1);
        }
        (void)close(pipe_fd);
}